﻿using bleCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.GenericAttributeProfile;

namespace bleCtrlCenter
{
    internal class Program
    {
        static bool ready = false;

        static List<ClientConfig> setConfig() 
        {
            List<ClientConfig> clientConfig = new List<ClientConfig>();
            var mac_list = File.ReadAllLines("./mac.txt");
            foreach (var mac in mac_list)
            {
                var c = mac.Trim();
                if (c.StartsWith("#")) continue;
                if (c == "") continue;
                var ca = c.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                clientConfig.Add(new ClientConfig()
                {
                    MAC = ca[0],
                    NAME = ca.Length > 1 ? ca[1] : ca[0],
                    GATT_LIST = new string[] { Consts.GATT_TEMPERATURE }
                });
            }

            return clientConfig;
        }

        static void Main(string[] args)
        {
            DeviceManager.BleDiscoveryFinished += DeviceManager_BleDiscoveryFinished;
            DeviceManager.Discovery(setConfig());
            DeviceManager.BleDataReceived += DeviceManager_BleDataReceived;
            Console.Read();
            
        }

        private static void DeviceManager_BleDataReceived(MyBleDevice device, GattCharacteristic sender, byte[] data)
        {
            if (sender.Uuid == new Guid(Consts.GATT_TEMPERATURE))
            {
                var msg = String.Format("#来自设备{0}的信息：温度：{1}，记录时间{2}", device, data[0], DateTime.Now);
                Logger.LogMsg(msg);
            }
        }

        private static void DeviceManager_BleDiscoveryFinished()
        {
            Console.WriteLine("共发现设备{0}个", DeviceManager.GetOnLineClients().Count);
            foreach (var client in DeviceManager.GetOnLineClients())
            {
                Console.WriteLine(client.NAME);
                foreach (var notifier in client.Notifier)
                {
                    client.EnableGattReceive(notifier.Uuid.ToString());
                }
            }
            ready = true;
        }
    }
}
